<?php
namespace app\home\controller;

use app\common\model\UserPlatoon as UserPlatoonModel;
use app\common\model\AppointmentRich as AppointmentRichModel;
use app\common\model\AppointmentUpstart as AppointmentUpstartModel;

use app\common\component\user\UserModel;
use app\common\component\user_platoon\UserPlatoonService;
use app\common\component\user_platoon_log\UserPlatoonLogService;
use app\common\component\appointment_upstart\AppointmentUpstartService;

class AppointmentUpstart extends ControllerBase {
	public function _initialize() {
		$this -> checkLogin();

		if(getParam('UPSTART_IS_OPEN') == 0) {
			echo '<meta charset="utf-8"><script>alert("土豪区已关闭!");window.history.go(-1);</script>';exit;
		}
	}

	public function index() {
		/*
		$selectAppointmentUpstart = AppointmentUpstartModel::where('status = 0 AND create_time < ' . (time() - (48 * 60 * 60))) -> select();
		foreach($selectAppointmentUpstart as $appointmentUpstart) {
			$appointmentUpstart -> status = 1;
			$appointmentUpstart -> save();
		}
		*/

		$this -> view -> assign('appointmentUpstarts', AppointmentUpstartModel::where('user_id', \think\Session::get('user_id')) -> order('help_appointment_upstart_id DESC') -> paginate(10, true));

		return $this -> view -> fetch();
	}

	public function create() {
		$post = $this -> request -> post();

		if($this -> validate($post, ['appointment_price' => 'require|token']) !== true) {
			echo '<meta charset="utf-8"><script>alert("请勿重复提交!");window.history.go(-1);</script>';exit;
		}
		unset($post['__token__']);

		$post['user_id'] = \think\Session::get('user_id');

		if($post['appointment_price'] < 200) {
    		echo '<meta charset="utf-8"><script>alert("您预约的' . $post['appointment_price'] . '金额小于指定金额!");window.history.go(-1);</script>';exit;
		}

		$userIds = UserModel::where('promotion_id', $post['user_id']) -> column('user_id');
		$totalPromotion = count($userIds);
		$userIdsStr = '';
		foreach($userIds as $userId) {
			$userIdsStr .= $userId . ',';
		}
		$userIdsStr = substr($userIdsStr, 0, -1);

		if(!empty($userIdsStr)) {
			$totalPPromotion = UserModel::where('promotion_id in(' . $userIdsStr . ')') -> count();
			$totalP = $totalPPromotion + $totalPromotion;
	
			if($totalPromotion >= 15 && $totalP >= 80) {
				if($post['appointment_price'] > 1000) {
		    		echo '<meta charset="utf-8"><script>alert("您预约的最高预约金额为1000!");window.history.go(-1);</script>';exit;
				}
			} else if($totalPromotion >= 10 && $totalP >= 30) {
				if($post['appointment_price'] > 800) {
		    		echo '<meta charset="utf-8"><script>alert("您预约的最高预约金额为800!");window.history.go(-1);</script>';exit;
				}
			} else if($totalPromotion >= 5 && $totalP >= 10) {
				if($post['appointment_price'] > 600) {
		    		echo '<meta charset="utf-8"><script>alert("您预约的最高预约金额为600!");window.history.go(-1);</script>';exit;
				}
			} else {
				if($post['appointment_price'] > 500) {
		    		echo '<meta charset="utf-8"><script>alert("您预约的最高预约金额为500!");window.history.go(-1);</script>';exit;
				}
			}
		} else {
			if($post['appointment_price'] > 500) {
	    		echo '<meta charset="utf-8"><script>alert("您预约的最高预约金额为500!");window.history.go(-1);</script>';exit;
			}
		}

		$currentTime = time();
		$APPOINTMENT_TIME = getParam('APPOINTMENT_TIME');
		$findHelpAppointmentUpstart = AppointmentUpstartModel::where('user_id', $post['user_id']) -> where('status', 0) -> where('create_time', '>', $currentTime - ($APPOINTMENT_TIME * 60 * 60)) -> find();
		if($findHelpAppointmentUpstart) {
			echo '<meta charset="utf-8"><script>alert("您的预约在' . $APPOINTMENT_TIME . '小时内，请耐心等候匹配!");window.history.go(-1);</script>';exit;
		}

		$findHelpAppointmentRich = AppointmentRichModel::where('user_id', $post['user_id']) -> where('status', 0) -> where('create_time', '>', $currentTime - ($APPOINTMENT_TIME * 60 * 60)) -> find();
		if($findHelpAppointmentRich) {
			echo '<meta charset="utf-8"><script>alert("您的预约在' . $APPOINTMENT_TIME . '小时内，请耐心等候匹配!");window.history.go(-1);</script>';exit;
		}

		$resultGetUserPlatoon = (new UserPlatoonService) -> getUserPlatoonId($post['user_id']);
		$platoon = round($post['appointment_price'] / getParam('PLATOON_GET_PRICE') / 100);
		if($resultGetUserPlatoon['data']['user_platoon'] -> price <= 0 || $resultGetUserPlatoon['data']['user_platoon'] -> price < $platoon) {
			echo '<meta charset="utf-8"><script>alert("您的排单币不足!");window.history.go(-1);</script>';exit;
		}

		\think\Db::startTrans();
		try {
			$resultHelpAppointmentUpstart = (new AppointmentUpstartService()) -> appointment($post);
			if($resultHelpAppointmentUpstart['code'] !== 0) {
    			throw new \Exception($resultHelpAppointmentUpstart['message']);
    		}

			$userName = \think\Session::get('user_name');
			$resultUserPlatoonLogService = (new UserPlatoonLogService()) -> log(2, 0, $platoon, $userName, $userName, '排单币使用', 1);
			if($resultUserPlatoonLogService['code'] != 0) {
				throw new \Exception($resultUserPlatoonLogService['message']);
			}

			if(!UserPlatoonModel::where('user_id', $post['user_id']) -> setDec('price', $platoon)) {
				throw new \Exception('预约失败');
			}

			\think\Db::commit();
		} catch(\Exception $e) {
			\think\Db::rollback();

			echo '<meta charset="utf-8"><script>alert("' . $e -> getMessage() . '!");window.history.go(-1);</script>';exit;
		}

		echo '<meta charset="utf-8"><script>alert("' . $resultHelpAppointmentUpstart['message'] . '!");window.location.href="/appointment/upstart";</script>';exit;
	}
}
?>